<template>
  <div class="finance-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left-actions">
        <el-button type="primary" @click="showIncomeDialog = true">
          <el-icon><Plus /></el-icon>
          新增收入
        </el-button>
        <el-button type="warning" @click="showExpenseDialog = true">
          <el-icon><Minus /></el-icon>
          新增支出
        </el-button>
        <el-button type="success" @click="exportFinanceData">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
      </div>
      <div class="right-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-select v-model="filterType" placeholder="交易类型" style="width: 120px" clearable>
          <el-option label="全部" value="" />
          <el-option label="收入" value="income" />
          <el-option label="支出" value="expense" />
        </el-select>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 财务概览卡片 -->
    <el-row :gutter="20" class="finance-overview">
      <el-col :span="6">
        <div class="overview-card income">
          <div class="card-icon">
            <el-icon :size="32"><TrendCharts /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-title">总收入</div>
            <div class="card-amount">¥{{ formatNumber(financeStats.totalIncome) }}</div>
            <div class="card-change positive">+{{ financeStats.incomeChange }}%</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="overview-card expense">
          <div class="card-icon">
            <el-icon :size="32"><TrendCharts /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-title">总支出</div>
            <div class="card-amount">¥{{ formatNumber(financeStats.totalExpense) }}</div>
            <div class="card-change negative">+{{ financeStats.expenseChange }}%</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="overview-card profit">
          <div class="card-icon">
            <el-icon :size="32"><Money /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-title">净利润</div>
            <div class="card-amount">¥{{ formatNumber(financeStats.netProfit) }}</div>
            <div class="card-change" :class="financeStats.profitChange >= 0 ? 'positive' : 'negative'">
              {{ financeStats.profitChange >= 0 ? '+' : '' }}{{ financeStats.profitChange }}%
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="overview-card today">
          <div class="card-icon">
            <el-icon :size="32"><Calendar /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-title">今日收入</div>
            <div class="card-amount">¥{{ formatNumber(financeStats.todayIncome) }}</div>
            <div class="card-subtitle">{{ financeStats.todayTransactions }} 笔交易</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 收支趋势图 -->
      <el-col :span="16">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">收支趋势</span>
              <el-radio-group v-model="trendChartType" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">本年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="trendChartOption" :loading="chartLoading" />
          </div>
        </el-card>
      </el-col>
      
      <!-- 收入构成饼图 -->
      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">收入构成</span>
              <el-button type="text" size="small" @click="refreshIncomeChart">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="incomeChartOption" :loading="chartLoading" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易记录表格 -->
    <el-card class="transaction-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">交易记录</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索交易描述、订单号"
              style="width: 250px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>
      
      <el-table
        :data="filteredTransactions"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="transactionNumber" label="交易单号" width="150" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'income' ? 'success' : 'warning'" size="small">
              {{ row.type === 'income' ? '收入' : '支出' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="amount" label="金额" width="120" sortable>
          <template #default="{ row }">
            <span :class="row.type === 'income' ? 'income-amount' : 'expense-amount'">
              {{ row.type === 'income' ? '+' : '-' }}¥{{ formatNumber(row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100" />
        <el-table-column prop="relatedOrder" label="关联订单" width="150" />
        <el-table-column prop="operator" label="操作员" width="100" />
        <el-table-column prop="createTime" label="交易时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="viewTransactionDetail(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="text" 
              size="small" 
              @click="confirmTransaction(row)"
            >
              确认
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="text" 
              size="small" 
              @click="cancelTransaction(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalTransactions"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 收入对话框 -->
    <IncomeDialog
      v-model="showIncomeDialog"
      @success="handleIncomeSuccess"
    />

    <!-- 支出对话框 -->
    <ExpenseDialog
      v-model="showExpenseDialog"
      @success="handleExpenseSuccess"
    />

    <!-- 交易详情对话框 -->
    <TransactionDetailDialog
      v-model="showTransactionDetailDialog"
      :transaction="selectedTransaction"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Minus,
  Download,
  Refresh,
  Search,
  TrendCharts,
  Money,
  Calendar
} from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import IncomeDialog from './components/IncomeDialog.vue'
import ExpenseDialog from './components/ExpenseDialog.vue'
import TransactionDetailDialog from './components/TransactionDetailDialog.vue'
import { getFinanceStats, getTransactionList, exportFinanceReport } from '@/api/finance'
import dayjs from 'dayjs'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const dateRange = ref([dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')])
const filterType = ref('')
const searchKeyword = ref('')
const showIncomeDialog = ref(false)
const showExpenseDialog = ref(false)
const showTransactionDetailDialog = ref(false)
const selectedTransaction = ref(null)
const chartLoading = ref(false)
const trendChartType = ref('month')
const currentPage = ref(1)
const pageSize = ref(20)
const totalTransactions = ref(0)
const selectedTransactions = ref([])

// 财务统计数据
const financeStats = reactive({
  totalIncome: 1256800,
  totalExpense: 456200,
  netProfit: 800600,
  todayIncome: 45680,
  incomeChange: 12.5,
  expenseChange: 8.3,
  profitChange: 15.2,
  todayTransactions: 23
})

// 交易记录列表
const transactionList = ref([
  {
    id: 1,
    transactionNumber: 'T202412250001',
    type: 'income',
    category: '房费收入',
    description: '301房间住宿费',
    amount: 888,
    paymentMethod: '微信支付',
    relatedOrder: 'R202412250001',
    operator: '张三',
    createTime: new Date(),
    status: 'completed'
  },
  {
    id: 2,
    transactionNumber: 'T202412250002',
    type: 'income',
    category: '餐饮收入',
    description: '客房送餐服务',
    amount: 128,
    paymentMethod: '支付宝',
    relatedOrder: 'F202412250001',
    operator: '李四',
    createTime: new Date(Date.now() - 30 * 60 * 1000),
    status: 'completed'
  },
  {
    id: 3,
    transactionNumber: 'T202412250003',
    type: 'expense',
    category: '采购支出',
    description: '客房用品采购',
    amount: 2500,
    paymentMethod: '银行转账',
    relatedOrder: 'P202412250001',
    operator: '王五',
    createTime: new Date(Date.now() - 60 * 60 * 1000),
    status: 'pending'
  },
  {
    id: 4,
    transactionNumber: 'T202412250004',
    type: 'expense',
    category: '人员工资',
    description: '12月员工工资',
    amount: 45000,
    paymentMethod: '银行转账',
    relatedOrder: '',
    operator: '赵六',
    createTime: new Date(Date.now() - 2 * 60 * 60 * 1000),
    status: 'completed'
  }
])

// 计算属性
const filteredTransactions = computed(() => {
  let filtered = transactionList.value
  
  // 按类型过滤
  if (filterType.value) {
    filtered = filtered.filter(transaction => transaction.type === filterType.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(transaction => 
      transaction.description.toLowerCase().includes(keyword) ||
      transaction.transactionNumber.toLowerCase().includes(keyword) ||
      transaction.relatedOrder.toLowerCase().includes(keyword)
    )
  }
  
  // 按日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    filtered = filtered.filter(transaction => {
      const transactionDate = dayjs(transaction.createTime).format('YYYY-MM-DD')
      return transactionDate >= startDate && transactionDate <= endDate
    })
  }
  
  totalTransactions.value = filtered.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 图表配置
const trendChartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  legend: {
    data: ['收入', '支出', '净利润']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '¥{value}'
    }
  },
  series: [
    {
      name: '收入',
      type: 'line',
      smooth: true,
      data: [85000, 92000, 88000, 95000, 102000, 98000, 105000, 110000, 108000, 115000, 120000, 125000],
      itemStyle: {
        color: '#67c23a'
      }
    },
    {
      name: '支出',
      type: 'line',
      smooth: true,
      data: [35000, 38000, 36000, 40000, 42000, 39000, 43000, 45000, 44000, 46000, 48000, 50000],
      itemStyle: {
        color: '#f56c6c'
      }
    },
    {
      name: '净利润',
      type: 'line',
      smooth: true,
      data: [50000, 54000, 52000, 55000, 60000, 59000, 62000, 65000, 64000, 69000, 72000, 75000],
      itemStyle: {
        color: '#409eff'
      }
    }
  ]
})

const incomeChartOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '收入构成',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 856000, name: '房费收入' },
        { value: 156000, name: '餐饮收入' },
        { value: 89000, name: '会议收入' },
        { value: 45000, name: '其他收入' }
      ]
    }
  ]
})

// 方法
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

const formatDateTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusType = (status) => {
  const statusMap = {
    completed: 'success',
    pending: 'warning',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    completed: '已完成',
    pending: '待确认',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const handleDateChange = () => {
  // 日期变化时重新加载数据
  loadTransactionData()
}

const handleSelectionChange = (selection) => {
  selectedTransactions.value = selection
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewTransactionDetail = (transaction) => {
  selectedTransaction.value = transaction
  showTransactionDetailDialog.value = true
}

const confirmTransaction = async (transaction) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认交易 ${transaction.transactionNumber} 吗？`,
      '确认交易',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    transaction.status = 'completed'
    ElMessage.success('交易已确认')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认交易失败')
    }
  }
}

const cancelTransaction = async (transaction) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消交易 ${transaction.transactionNumber} 吗？`,
      '取消交易',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    transaction.status = 'cancelled'
    ElMessage.success('交易已取消')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消交易失败')
    }
  }
}

const refreshIncomeChart = async () => {
  chartLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('图表已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    chartLoading.value = false
  }
}

const exportFinanceData = async () => {
  try {
    ElMessage.info('正在导出财务报表...')
    // 调用导出API
    // await exportFinanceReport({
    //   startDate: dateRange.value[0],
    //   endDate: dateRange.value[1],
    //   type: filterType.value
    // })
    
    // 模拟导出
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('财务报表导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const refreshData = async () => {
  try {
    await loadData()
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  }
}

const handleIncomeSuccess = () => {
  showIncomeDialog.value = false
  refreshData()
}

const handleExpenseSuccess = () => {
  showExpenseDialog.value = false
  refreshData()
}

const loadFinanceStats = async () => {
  try {
    // const stats = await getFinanceStats()
    // Object.assign(financeStats, stats)
  } catch (error) {
    console.error('加载财务统计失败:', error)
  }
}

const loadTransactionData = async () => {
  try {
    // const transactions = await getTransactionList({
    //   startDate: dateRange.value[0],
    //   endDate: dateRange.value[1],
    //   type: filterType.value,
    //   page: currentPage.value,
    //   pageSize: pageSize.value
    // })
    // transactionList.value = transactions.list
    // totalTransactions.value = transactions.total
  } catch (error) {
    console.error('加载交易数据失败:', error)
  }
}

const loadData = async () => {
  await Promise.all([
    loadFinanceStats(),
    loadTransactionData()
  ])
}

// 监听图表类型变化
watch(trendChartType, async (newType) => {
  chartLoading.value = true
  try {
    // 根据类型加载不同的数据
    await new Promise(resolve => setTimeout(resolve, 500))
  } finally {
    chartLoading.value = false
  }
})

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.finance-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 84px);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .left-actions {
    display: flex;
    gap: 12px;
  }
  
  .right-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.finance-overview {
  margin-bottom: 20px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
  
  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    margin-right: 20px;
  }
  
  .card-content {
    flex: 1;
    
    .card-title {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 8px;
    }
    
    .card-amount {
      font-size: 28px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .card-change {
      font-size: 12px;
      
      &.positive {
        color: #67c23a;
      }
      
      &.negative {
        color: #f56c6c;
      }
    }
    
    .card-subtitle {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
  
  &.income .card-icon {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  }
  
  &.expense .card-icon {
    background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  }
  
  &.profit .card-icon {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  }
  
  &.today .card-icon {
    background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
  }
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  
  .chart-container {
    height: 320px;
  }
}

.transaction-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
}

.income-amount {
  color: #67c23a;
  font-weight: 600;
}

.expense-amount {
  color: #f56c6c;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

// 响应式设计
@media (max-width: 1200px) {
  .charts-section {
    .el-col {
      margin-bottom: 20px;
    }
  }
}

@media (max-width: 768px) {
  .finance-container {
    padding: 10px;
  }
  
  .operation-bar {
    flex-direction: column;
    gap: 16px;
    
    .left-actions,
    .right-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }
  
  .finance-overview {
    .el-col {
      margin-bottom: 12px;
    }
  }
  
  .overview-card {
    padding: 16px;
    
    .card-icon {
      width: 50px;
      height: 50px;
      margin-right: 16px;
    }
    
    .card-content .card-amount {
      font-size: 24px;
    }
  }
  
  .chart-card {
    height: 300px;
    
    .chart-container {
      height: 220px;
    }
  }
}
</style>